// Copyright (c) 2019 Presto Labs Pte. Ltd.
// Author: jaewon

#include "coin1/fastfeed/view/json_object_table_builder.h"

#include <utility>

#include <glog/logging.h>

namespace fastfeed {
namespace view {

bool JsonObjectTableBuilder::UpdateByProto(const proto::Feed& feed) {
  switch (feed.data_type()) {
    case proto::DATA_TYPE_JSON_OBJECT_TABLE_SNAPSHOT:
      table_.clear();
      break;

    case proto::DATA_TYPE_JSON_OBJECT_TABLE_UPDATE:
      break;

    default:
      LOG(ERROR) << "Unsupported data type: " << feed.data_type();
      return false;
  }

  UpdateHeader(feed);
  for (const auto& row : feed.json_object_table()) {
    switch (row.action()) {
      case proto::TABLE_ACTION_INSERT:
        Insert(row);
        break;

      case proto::TABLE_ACTION_UPDATE:
        Update(row);
        break;

      case proto::TABLE_ACTION_DELETE:
        Delete(row);
        break;

      default:
        LOG(FATAL) << "Unsupported table action: " << row.action();
    }
  }
  return true;
}

void JsonObjectTableBuilder::Insert(const proto::JsonObjectTableRow& row) {
  nlohmann::json value = nlohmann::json::parse(row.json_object());
  table_[row.key()] = std::move(value);
}

void JsonObjectTableBuilder::Update(const proto::JsonObjectTableRow& row) {
  nlohmann::json value = nlohmann::json::parse(row.json_object());
  nlohmann::json& elem = table_[row.key()];
  elem.update(value);
}

void JsonObjectTableBuilder::Delete(const proto::JsonObjectTableRow& row) {
  table_.erase(row.key());
}

}  // namespace view
}  // namespace fastfeed
